package com.firegod.group.service.impl;

import com.firegod.commonutils.result.ResultCode;
import com.firegod.group.form.TopicForm;
import com.firegod.group.service.TopicService;
import com.firegod.servicebase.dao.CommentRepository;
import com.firegod.servicebase.dao.GroupRepository;
import com.firegod.servicebase.dao.TopicRepository;
import com.firegod.servicebase.dao.UserRepository;
import com.firegod.servicebase.entity.*;
import com.firegod.servicebase.exceptionhandler.exception.GuliException;
import com.firegod.shiro.service.TokenService;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

import static java.util.stream.Collectors.toList;

@Service
public class TopicServiceImpl implements TopicService {

    @Autowired
    private TopicRepository topicRepository;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private GroupRepository groupRepository;
    @Autowired
    private TopicService topicService;

    @Autowired
    private CommentRepository commentRepository;

    @Override
    public String sendTopic(String groupId, String title, String describe) {
        if (groupId == null)
            throw GuliException.from(ResultCode.GROUP_ID_NOT_EXIST);
        if (title == null)
            throw GuliException.from(ResultCode.NO_TITLE);

        System.out.println("发帖:id:" + groupId + " title:" + title + " describe: " + describe);
        Topic topic = new Topic();
        topic.setTitle(title);
        topic.setTopicDescribe(describe);

        Group group = groupRepository.getGroupByGroupId(groupId);
        if (group == null) {
            throw GuliException.from(ResultCode.GROUP_ID_NOT_EXIST);
        }
        topic.setGroup(group);

        String userId = tokenService.getUserId();
        User user = userRepository.getByUserId(userId);
        topic.setUser(user);
        topic.setDate(new Date());

        String topicId = RandomStringUtils.randomAlphanumeric(16);
        while (topicRepository.getTopicByTopicId(topicId) != null) {
            topicId = RandomStringUtils.randomAlphanumeric(16);
        }
        topic.setTopicId(topicId);

        topicRepository.saveAndFlush(topic);
        return topic.getTopicId();
    }

    @Override
    public void deleteTopic(String topicId) {
        Topic topic = topicRepository.getTopicByTopicId(topicId);
        if (null == topic) {
            throw GuliException.from(ResultCode.TOPIC_NOT_EXIST);
        }
        //老师能删除自己的课程圈子内的所有帖子
        if (!tokenService.isStudent()) {
            var group = topic.getGroup();
            var course = group.getCourse();
            var teacher = course.getTeacher();
            String teacherId = teacher.getUserId();
            if (!teacherId.equals(tokenService.getUserId()))
                throw GuliException.from("您不能删除其他老师圈子内的贴子！");
        } else if (!tokenService.getUserId().equals(topic.getUser().getUserId())) {
            throw GuliException.from("您不能删除其他用户的帖子！");
        }

        List<Comment> comments = topic.getTopicCommentList();
        for (var comment : comments) {
            commentRepository.delete(comment);
        }
        commentRepository.flush();
        topicRepository.delete(topic);
        topicRepository.flush();
    }

    @Override
    public void updateTopic(String topicId, String title, String describe) {
        Topic topic = topicRepository.getTopicByTopicId(topicId);
        if (null == topic) {
            throw GuliException.from(ResultCode.TOPIC_NOT_EXIST);
        }
        if (null == title) {
            throw GuliException.from(ResultCode.NO_TITLE);
        }
        if (null == describe) {
            throw GuliException.from("帖子内容不存在！");
        }
        topic.setTitle(title);
        topic.setTopicDescribe(describe);
        topicRepository.saveAndFlush(topic);
    }

    @Override
    public boolean likeTopic(String topicId) {
        try {
            Topic topic = topicRepository.getTopicByTopicId(topicId);
            int likeNum = topic.getLikeNum();
            if (likeNum == 1)
                return true;

            String userId = tokenService.getUserId();
            User user = userRepository.getByUserId(userId);
            topic.like(user);

            topicRepository.saveAndFlush(topic);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public boolean unLikeTopic(String topicId) {
        try {
            Topic topic = topicRepository.getTopicByTopicId(topicId);
            int likeNum = topic.getLikeNum();
            if (likeNum == 0) {
                return true;
            }

            String userId = tokenService.getUserId();
            User user = userRepository.getByUserId(userId);
            topic.unlike(user);

            topicRepository.saveAndFlush(topic);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public void featureTopic(String topicId, boolean isFeature) {
        Topic topic = topicRepository.getTopicByTopicId(topicId);
        if (topic == null)
            throw GuliException.from(ResultCode.TOPIC_NOT_EXIST);
        topic.setFeature(isFeature);
        topicRepository.saveAndFlush(topic);
    }

    @Override
    public void topTopic(String topicId, boolean isTop) {
        Topic topic = topicRepository.getTopicByTopicId(topicId);
        if (topic == null)
            throw GuliException.from(ResultCode.TOPIC_NOT_EXIST);
        topic.setTop(isTop);
        topicRepository.saveAndFlush(topic);
    }

    @Override
    public List<TopicForm> getTopicList(String courseId) {
        Group group = groupRepository.getGroupByGroupId(courseId);
        if (null == group)
            throw GuliException.from(ResultCode.GROUP_ID_NOT_EXIST);
        List<Topic> topics = group.getTopicList();
        List<TopicForm> topicForms = new ArrayList<>();
        for (var topic : topics) {
            TopicForm topicForm = new TopicForm();
            topicForm.setIsTop(topic.getTop());
            topicForm.setIsFeature(topic.getFeature());
            topicForm.setTopicDate(topic.getDate());
            topicForm.setTopicDescribe(topic.getTopicDescribe());
            topicForm.setUserId(topic.getUser().getUserId());
            topicForm.setUserName(topic.getUser().getName());
            topicForm.setTopicId(topic.getTopicId());
            topicForm.setTopicTitle(topic.getTitle());
            User user = userRepository.getByUserId(topicForm.getUserId());
            topicForm.setTea(user instanceof Teacher);

            topicForms.add(topicForm);
        }
        return topicForms.stream().sorted(
                Comparator.comparing(TopicForm::getIsTop
                ).thenComparing(TopicForm::getIsFeature
                ).thenComparing(TopicForm::getTopicDate).reversed()
        ).collect(toList());
    }

    @Override
    public List<Topic> getTopTopics(String groupId) {
        if (groupId == null)
            throw GuliException.from(ResultCode.GROUP_ID_NOT_EXIST);
        List<Topic> topics = topicRepository.findAll();
        return topics.stream().filter(Topic::getTop).sorted((o1, o2) -> o2.getDate().compareTo(o1.getDate())).collect(toList());
    }

    @Override
    public HashMap<String, Object> getTopicInfo(String topicId) {
        HashMap<String, Object> hashMap = new HashMap<>();

        Topic topic = topicRepository.getTopicByTopicId(topicId);
        if (topic == null)
            throw GuliException.from(ResultCode.TOPIC_NOT_EXIST);
        hashMap.put("topicId", topicId);
        hashMap.put("topicTitle", topic.getTitle());
        hashMap.put("topicDescribe", topic.getTopicDescribe());
        hashMap.put("isTop", topic.getTop());
        hashMap.put("isFeature", topic.getFeature());
        System.out.println("帖子详情 hashMap" + hashMap);
        return hashMap;
    }
}
